package com.gcloud.controller.compute.config;

import com.gcloud.common.util.StringUtils;
import com.gcloud.controller.compute.dispatcher.DispatcherSelector;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
Copyright (c) [2020] [G-CLOUD TECHNOLOGY] [G-Cloud 8.0] is licensed under the Mulan PSL v1.
You can use this software according to the terms and conditions of the Mulan PSL v1. You may obtain
a copy of Mulan PSL v1 at: http://license.coscl.org.cn/MulanPSL THIS SOFTWARE IS PROVIDED ON AN 
"AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v1 for more details.
 */


@Component
@Slf4j
public class DispatcherPrimaryConfig implements ApplicationContextAware {

    @Value("${gcloud.controller.compute.dispatcherStrategy:}")
    private String dispatcherStrategy;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        DispatcherSelector selector = StringUtils.isBlank(dispatcherStrategy) ? null : DispatcherSelector.value(dispatcherStrategy);
        if(selector == null){
            selector = DispatcherSelector.SIMPLE;
        }
        log.debug("DispatcherPrimaryConfig " + selector.getImpl().getSimpleName());

        AutowireCapableBeanFactory factory = applicationContext.getAutowireCapableBeanFactory();
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) factory;
        BeanDefinition beanDefinition = registry.getBeanDefinition(StringUtils.toLowerCaseFirstOne(selector.getImpl().getSimpleName()));
        beanDefinition.setPrimary(true);

    }

	public String getDispatcherStrategy() {
		return dispatcherStrategy;
	}

	public void setDispatcherStrategy(String dispatcherStrategy) {
		this.dispatcherStrategy = dispatcherStrategy;
	}

}